package evil.wolf.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JOptionPane;

public class DatabaseManager {

	Statement statement;
	ConnectDatabase conn = new ConnectDatabase();
	
	public DatabaseManager() {
		openConnection();
	}
	
	public void openConnection() {
		try {
			conn = new ConnectDatabase();
			statement = conn.getConnection().createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void closeConnect() {
		  try {
		      if (statement != null) {
		        statement.close();
		      }
		      if (conn != null) {
		    	  conn.getConnection().close();
		      }
		    } catch (Exception e) {
		    	JOptionPane.showMessageDialog(null,
		    			"Could not close the current connection.", "ERROR", JOptionPane.INFORMATION_MESSAGE);
		    	System.out.println("Could not close the current connection.");
		      	e.printStackTrace();
		    }
	}
	
	public ResultSet getResultSet(String sql)	{
		ResultSet rs = null;
		try {
			rs = statement.executeQuery(sql);
		} catch (SQLException e) {
			System.out.println("Could not initialize the database.");
			e.printStackTrace();
		}
		return rs;
	}
	
	public boolean excuteQuery(String sql){
		try {
			PreparedStatement pst = conn.getConnection().prepareStatement(sql);
			pst.executeQuery();
			return true;
		} catch (SQLException e) {
			System.out.print("Thao tac khong thanh cong");
			JOptionPane.showMessageDialog(null,"Thao tac khong thanh cong."
			+ "\n" + "Nguyen nhan:\n" + e.toString(), "ERROR", JOptionPane.INFORMATION_MESSAGE);
			e.printStackTrace();
			return false;
		}
	}
	
//	public int countNumberOfResultSet(ResultSet rs) {
//		int number = 0;
//		try {
//			while(rs.next())
//				number ++;
//		} catch (SQLException e) {
//
//			e.printStackTrace();
//		}
//		return number;
//	}
}
